package pacs_server

import (
	"gitee.com/uni-minds/bridge-pacs/global"
	"gitee.com/uni-minds/bridge-pacs/tools"
)

func (pi *PacsServer) ImportStudies(data global.Dcm4cheStudiesInfo) (detail ImportDetails, err error) {
	importStudiesId := data.StudiesId
	importSeriesInfos := data.SeriesInfo

	pi.Logf("-   studies import: %s", importStudiesId)

	// 不存在的Series先添加到序列中，之后入库
	newImportSeriesInfos := make([]global.Dcm4cheSeriesInfo, 0)

	if dbStudiesInfo, err := pi.FindStudiesByIdWithHiddenLocal(importStudiesId); err != nil {
		// 不存在StudiesId
		importStudiesInfo := global.StudiesInfo{
			StudiesId:           importStudiesId,
			StudyDatetime:       tools.TimeEncodeString(data.StudyDatetime),
			PatientId:           data.PatientId,
			PatientName:         data.PatientName,
			IncludeSeries:       "",
			RecordDatetime:      tools.TimeEncodeNow(),
			UpdateDatetime:      0,
			DbHidden:            0,
			DbDelete:            0,
			OwnerGroups:         "",
			LabelUpdateDatetime: 0,
			LabelUidAuthor:      0,
			LabelUidReview:      0,
			LabelHisInfo:        "",
			LabelProgress:       0,
			LabelMemo:           "",
			LabelInfoAttend:     "",
		}

		if err = pi.dbCreateStudies(importStudiesInfo); err != nil {
			pi.Log("E db import studies", err.Error())
			return detail, err
		}

		detail.CountStudies++
		detail.ImportStudies = append(detail.ImportStudies, importStudiesId)

		newImportSeriesInfos = importSeriesInfos

	} else {
		// 存在StudiesId，匹配SeriesId

		for _, importSeriesInfo := range importSeriesInfos {
			if !tools.IdStrCheckId(dbStudiesInfo.IncludeSeries, importSeriesInfo.SeriesId) {
				// 不存在SeriesId
				newImportSeriesInfos = append(newImportSeriesInfos, importSeriesInfo)
			}
		}
	}

	// 按顺序开始添加Series
	for i, importSeriesInfo := range newImportSeriesInfos {
		seriesId := importSeriesInfo.SeriesId

		if di, err := pi.ImportSeries(importSeriesInfo, importStudiesId); err != nil {
			pi.Log("E db import series:", importSeriesInfo.SeriesId)
		} else if err = pi.StudiesInsertSeriesId(importStudiesId, seriesId); err != nil {
			pi.Log("E db update studies:", err.Error())
		} else {
			pi.Logf("-   studies import %d/%d series %s", i+1, len(newImportSeriesInfos), seriesId)
			detail.CountSeries += di.CountSeries
			detail.CountInstance += di.CountInstance
		}
	}

	return detail, nil
}

func (pi *PacsServer) ImportSeries(data global.Dcm4cheSeriesInfo, studiesId string) (detail ImportDetails, err error) {
	importSeriesId := data.SeriesId
	importInstanceInfos := data.InstanceInfo

	pi.Logf("|-  series import %d: %s", data.SeriesNumber, importSeriesId)

	newImportInstanceInfos := make([]global.Dcm4cheInstanceInfo, 0)

	if dbSeriesInfo, err := pi.FindSeriesByIdLocal(importSeriesId); err != nil {
		// 不存在本地缓存
		importSeriesInfo := global.SeriesInfo{
			SeriesId:            importSeriesId,
			SeriesNumber:        data.SeriesNumber,
			StudiesId:           studiesId,
			PatientId:           data.PatientId,
			PatientName:         data.PatientName,
			URL:                 data.URL,
			IncludeInstances:    "",
			StudyDatetime:       tools.TimeEncodeString(data.StudyDatetime),
			RecordDatetime:      tools.TimeEncodeNow(),
			UpdateDatetime:      0,
			DbHidden:            0,
			DbDelete:            0,
			LabelMemo:           "",
			LabelInfoAttend:     "",
			LabelUpdateDatetime: 0,
		}

		pi.Log("|-  series not found, create now:", importSeriesId)

		if err = pi.dbCreateSeries(importSeriesInfo); err != nil {
			pi.Log("E db import series:", err.Error())
			return detail, err
		}

		detail.CountSeries++

		newImportInstanceInfos = importInstanceInfos

	} else {
		// 存在本地缓存
		pi.Log("|-  series found:", importSeriesId)

		for _, importInstanceInfo := range importInstanceInfos {
			_, err = pi.FindInstanceByIdLocal(importInstanceInfo.InstanceId)

			if !tools.IdStrCheckId(dbSeriesInfo.IncludeInstances, importInstanceInfo.InstanceId) {
				newImportInstanceInfos = append(newImportInstanceInfos, importInstanceInfo)
			}
		}
	}

	pi.Logf("|-  series has %d new instances: %s", len(newImportInstanceInfos), importSeriesId)

	for i, importInstanceInfo := range newImportInstanceInfos {
		instanceId := importInstanceInfo.InstanceId

		if di, err := pi.ImportInstance(importInstanceInfo, studiesId, importSeriesId); err != nil {
			pi.Log("E db import instance:", err.Error())
		} else if err = pi.SeriesUpdateInsertInstanceId(importSeriesId, instanceId); err != nil {
			pi.Log("E db update series:", err.Error())
		} else {
			detail.CountInstance += di.CountInstance
			pi.Logf("|-  series import instance %d/%d\n", i+1, len(newImportInstanceInfos))
		}
	}
	return detail, nil
}

func (pi *PacsServer) ImportInstance(data global.Dcm4cheInstanceInfo, studiesId string, seriesId string) (detail ImportDetails, err error) {
	importInstanceId := data.InstanceId

	pi.Logf("||- instance import %d: %s\n", data.InstanceNumber, importInstanceId)
	info, err := pi.FindInstanceByIdLocal(importInstanceId)

	if err != nil {
		//不存在本地缓存
		pi.Log("||- instance not found, create now: ", importInstanceId)

		info = global.InstanceInfo{
			InstanceId:          importInstanceId,
			InstanceNumber:      data.InstanceNumber,
			SeriesId:            seriesId,
			StudiesId:           studiesId,
			URL:                 data.URL,
			ContentDatetime:     tools.TimeEncodeString(data.ContentDatetime),
			RecordDatetime:      tools.TimeEncodeNow(),
			MediaWidth:          data.Width,
			MediaHeight:         data.Height,
			Frames:              data.Frames,
			FrameRate:           data.FrameRate,
			Duration:            -1,
			MediaType:           data.ContentType,
			CacheLocalPath:      "",
			DbHidden:            0,
			DbDelete:            0,
			LabelUpdateDatetime: 0,
			LabelView:           "",
			LabelDiagnose:       "",
			LabelInterfere:      "",
			LabelMemo:           "",
			LabelInfoAttend:     "",
		}

		if err = pi.dbCreateInstance(info); err != nil {
			return detail, err
		}

		detail.CountInstance++
	}

	if global.FlagGetChkMedia() {
		pi.Logf("||- instance check: %s", importInstanceId)

		if err = pi.InstanceMediaCheck(info.InstanceId, info.MediaType); err != nil {
			pi.Logf("||- instance media lost, regenerate: %s", info.InstanceId)
			_, err = pi.InstanceMediaGenerate(info.InstanceId, true)

		} else {
			pi.Log("...ok")
		}

		return detail, err
		// 存在条目且忽略缓存检查
	} else {
		// 忽略存在的条目
		pi.Log("||- instance found ignore media check: ", importInstanceId)
		return detail, nil

	}
}
